<?php
require_once(ROOT_DIR.'lib/utils/CProductDetail.php');
class CProduct
{
	static $conditionDefault = ',discount_percent,tax,market_price,discount_items,discount_maximum_items,discount_start_date,discount_end_date';
	static $categories = array();
	static function category($category_id)
	{
		if(!isset(CProduct::$categories[$category_id]))
		{
			CProduct::$categories[$category_id] = CStoreCategoryList::getInstance()->getOneRowsCate($category_id);
			//CProduct::$categories[$category_id] = CTable('cats//cat')->change_store(new CDataXmlStore('data/'.portal()->id.'/product_categories.xml'))->select($category_id);
		}
		return CProduct::$categories[$category_id];
	}
	static function update_substitute($id)
	{
		if(CPortal::$default == 'kultech')
		{
			if($product = CTable('product')->select($id, array('slave'=>false)))
			{
				if($product['reference_id'])
				{
					if(!($product = CTable('product')->select(array('code'=>$product['reference_id']), array('slave'=>false))))
					{
						return;
					}
				}

				if($product['quantity'] == 0 or $product['price'] == 0 or $product['min_price'] == 0 or $product['market_price'] == 0)
				{
					if($substitute = CTable('product')->select(EAnd(
						EEqual('reference_id',EString($product['code'])),
						EGT('price',EInt(0)),
						EGT('quantity',EInt(0)),
						EGT('min_price',EInt(0)),
						EGT('floor_price',EInt(0)),
						EGT('status',EInt(0)),
						EGT('market_price',EInt(0))
					), array('slave'=>false)))
					{

						CTable('product')->update(array('substitute_id'=>$substitute['id']), $product['id']);
					}
					elseif($product['substitute_id'])
					{
						CTable('product')->update(array('substitute_id'=>0), $product['id']);
					}
				}

			}
		}
	}

	static function get_new_products($cache_name=null, $cache_time=600, $clear_cache=false, $condition=false) {
		if ($cache_name==null) $cache_name = 'new_products_'.CPortal::$estore_id;
		if ($clear_cache || !($items=CSystem::$cachedata->get($cache_name))) {
		
			if(!$condition)
			{
				$condition = EAnd(
								 ELIKE('types',EString('.new.')),
								 ENE('category_id','phukien')
			//					 ,
			//					 EGT('price',EString(0)),EGT('min_price',EString(0)),
			//					 EGT('market_price',EString(0)),EGT('status',EString(0)),
			//					 EGT('quantity',EString(0)),ENE('thumbnail',EString(''))
							);
			}
			
			$items = array_values(CTable('product')->fields('id,name,unsigned_name,category_id,thumbnail,warranty,cache_properties, price'.CProduct::$conditionDefault)->select_all(
				$condition,
				array('order_by'=>'created_time desc', 'items_per_page'=>2,
					  'order_by'=>$this->order_by?$this->order_by:request('order_by'),
					  'page_no'=>$this->current_page?$this->current_page:request('page_no',0)+1,
					  'items_per_page'=>$this->items_per_page,)
			));
			foreach($items as &$item){
				$item['cache_properties'].='<strong>Thời gian bảo hành</strong>:&nbsp;'.$item['warranty'].'&nbsp;tháng';
				$item['name_short'] = CString(strip_tags($item['name']))->trim(15);

				$unsigned_name = isset($item['unsigned_name']) ? $item['unsigned_name'] : '';
				$param = array( 'id' => $item['id'], 'name' => $item['name'], 'category_id' => $item['category_id'], 'unsigned_name' => $unsigned_name);
				$item['onclick'] = url('product_detail', $param) . ' return false';
				$item['href'] = url('product_detail', $param, '', '1');
			}
			$items = CProductDetail::getProductDetailList($items);
			
			CSystem::$cachedata->set($cache_name, $items, $cache_time);
		}

		return $items;
	}
	
	static function get_not_new_products($cache_name=null, $cache_time=600, $clear_cache=false) {
		if ($cache_name==null) $cache_name = 'not_new_products_'.CPortal::$estore_id;
		if ($clear_cache || !($items=CSystem::$cachedata->get($cache_name))) {
			$items = array_values(CTable('product')->fields('id,name,unsigned_name,category_id,thumbnail,warranty,cache_properties, price'.CProduct::$conditionDefault)->select_all(
				EAnd(
					 ENLIKE('types',EString('.new.')),
					 ENE('category_id','phukien')
//					 ,
//					 EGT('price',EString(0)),EGT('min_price',EString(0)),
//					 EGT('market_price',EString(0)),EGT('status',EString(0)),
//					 EGT('quantity',EString(0)),ENE('thumbnail',EString(''))
				),
				array('order_by'=>'created_time desc', 'items_per_page'=>100)
			));
			foreach($items as &$item){
				$item['cache_properties'].='<strong>Thời gian bảo hành</strong>:&nbsp;'.$item['warranty'].'&nbsp;tháng';
				$item['name_short'] = CString(strip_tags($item['name']))->trim(15);

				$unsigned_name = isset($item['unsigned_name']) ? $item['unsigned_name'] : '';
				$param = array( 'id' => $item['id'], 'name' => $item['name'], 'category_id' => $item['category_id'], 'unsigned_name' => $unsigned_name);
				$item['onclick'] = url('product_detail', $param) . ' return false';
				$item['href'] = url('product_detail', $param, '', '1');
			}
			$items = CProductDetail::getProductDetailList($items);
			
			CSystem::$cachedata->set($cache_name, $items, $cache_time);
		}

		return $items;
	}
	
	static function get_accessories_products($cache_name=null, $cache_time=600, $clear_cache=false) {
			$items = array_values(CTable('product')->fields('id,name,unsigned_name,category_id,thumbnail,warranty,cache_properties, price, types'.CProduct::$conditionDefault)->select_all(
				EAnd(
					 ELIKE('category_id',EString('phukien'))
//					 ,
//					 EGT('price',EString(0)),EGT('min_price',EString(0)),
//					 EGT('market_price',EString(0)),EGT('status',EString(0)),
//					 EGT('quantity',EString(0)),ENE('thumbnail',EString(''))
				),
				array('order_by'=>'created_time desc', 'items_per_page'=>6)
			));
			foreach($items as &$item){
				$item['cache_properties'].='<strong>Thời gian bảo hành</strong>:&nbsp;'.$item['warranty'].'&nbsp;tháng';
				$item['name_short'] = CString(strip_tags($item['name']))->trim(11);

				$unsigned_name = isset($item['unsigned_name']) ? $item['unsigned_name'] : '';
				$param = array( 'id' => $item['id'], 'name' => $item['name'], 'category_id' => $item['category_id'], 'unsigned_name' => $unsigned_name);
				$item['onclick'] = url('product_detail', $param) . ' return false';
				$item['href'] = url('product_detail', $param, '', '1');
			}
			$items = CProductDetail::getProductDetailList($items);

		return $items;
	}

	static function get_typical_products($cache_name=null, $cache_time=620, $clear_cache=false) {
		if ($cache_name==null) $cache_name = 'typical_products_'.CPortal::$estore_id;
		if ($clear_cache || !($categories = CSystem::$cachedata->get($cache_name)) || DEBUG) {
			$file_name = 'data/'.portal()->id.'/product_categories.xml';
			if($data_categories = CTable('category')->select_all(EAnd(EEqual('feature', 1), ENE('parent_id', 0)), array('order_by' => 'id DESC', 'items_per_page'=>24))){
				foreach($data_categories as $k => $v){
					$v['idCate'] = $v['id'];
					$v['id'] = $v['char_seo'];
					$child_categories[$v['char_seo']] = $v;
				}
			}
			//debug($data_categories);
			//exit;
			//debug(CProduct::field_table('Nokia'));
			//exit;

			/*$child_categories = CTable('cats/cat/cats/cat/cats/cat[./is_homepage=1]')
				->change_store(new CDataXmlStore($file_name,'/root/'))->select_all(false, array('items_per_page'=>12));*/
			$categories = array();
			$count = 0;
			foreach ($child_categories as $key => $category) {
				if($count++ <18) {
					$products = CTable('product')->fields('id,name,thumbnail,unsigned_name')->select_all(EAnd(EEqual('category_id', EString($category['id'])),ELIKE('types',EString('special')),EEqual('reference_id',EString('')), EGT('price',EString(0)),EGT('min_price',EString(0)),EGT('market_price',EString(0)),EGT('status',EString(0)),EGT('quantity',EString(0)),EGT('thumbnail',EString(''))),array('items_per_page'=>4, 'fields'=>'id, name, price,thumbnail','order_by'=>'sort_order desc'));
					if(!$products) {
						$products = CTable('product')->fields('id,name,thumbnail,unsigned_name')->select_all(EAnd(EEqual('category_id', EString($category['id'])),EEqual('reference_id',EString('')), EGT('price',EString(0)),EGT('min_price',EString(0)),EGT('market_price',EString(0)),EGT('status',EString(0)),EGT('quantity',EString(0)),EGT('thumbnail',EString(''))),array('items_per_page'=>4, 'fields'=>'id, name, price,thumbnail','order_by'=>'sort_order desc'));
					}
					if (!empty($products)) {
						$category['href'] = url('product_list', array('category_id' => $category['id']), '', '1');
						$category['onclick'] = url('product_list', array('category_id' => $category['id'])) . ' return false;';
						$products = array_values($products);
						foreach ($products as &$item) {
							$unsigned_name = isset($item['unsigned_name']) ? $item['unsigned_name'] : '';
							$param = array( 'id' => $item['id'], 'name' => $item['name'], 'category_id' => $category['id'], 'unsigned_name' => $unsigned_name);
							$item['onclick'] = url('product_detail', $param) . ' return false';
							$item['href'] = url('product_detail', $param, '', '1');
						}
						$categories[] = $category + array('products' => array_values($products));
					} else {
					  $count--;
					}
				}
			}
			CSystem::$cachedata->set($cache_name, $categories, $cache_time);
		}
		return $categories;
	}

	static function listProductSpecialHot($category_id = '', $id = 0, $cache_name=null, $cache_time=630, $clear_cache=false){
		if ($cache_name==null) $cache_name = 'hot_product_'.$category_id.$id.'_'.CPortal::$estore_id;
		if ($clear_cache || !($items = CSystem::$cachedata->get($cache_name))) {
			$items = array_values(CTable('product')->fields('id,name,unsigned_name,category_id,thumbnail,warranty,cache_properties, price,special_image,product_vip')->select_all(
				EAnd(
					EEqual('category_id', EString($category_id)),
					ELIKE('types',EString('.special.')),ENE('id',EInt($id)),
					EGT('price',EString(0)),EGT('min_price',EString(0)),
					EGT('market_price',EString(0)),EGT('status',EString(0)),
					EGT('quantity',EString(0))
				),
				array('order_by'=>'product_vip desc, created_time desc', 'items_per_page'=>8)
			));
			foreach ($items as &$item) {
				$unsigned_name = isset($item['unsigned_name']) ? $item['unsigned_name'] : '';
				$param = array( 'id' => $item['id'], 'name' => $item['name'], 'category_id' => $item['category_id'], 'unsigned_name' => $unsigned_name);
				$item['onclick'] = url('product_detail', $param) . ' return false';
				$item['href'] = url('product_detail', $param, '', '1');
			}
			CSystem::$cachedata->set($cache_name, $items, $cache_time);
		}
		return $items;
	}

	static function getCateSpecial(){
		$items = array_values(CTable('product')->fields('id,name,unsigned_name,category_id,thumbnail,warranty,cache_properties,price,special_image,product_vip')->select_all(
			EAnd(
				EAnd(EEqual('product_vip',2)),ENE('special_image',EString('')),ELIKE('types',EString('.special.')),
				EGT('price',EString(0)),EGT('min_price',EString(0)),
				EGT('market_price',EString(0)),EGT('status',EString(0)),
				EGT('quantity',EString(0))
			),
			array('order_by'=>'product_vip desc, created_time desc', 'items_per_page'=>1)
		));
		foreach ($items as &$item) {
			$unsigned_name = isset($item['unsigned_name']) ? $item['unsigned_name'] : '';
			$param = array( 'id' => $item['id'], 'name' => $item['name'], 'category_id' => $item['category_id'], 'unsigned_name' => $unsigned_name);
			$item['onclick'] = url('product_detail', $param) . ' return false';
			$item['href'] = url('product_detail', $param, '', '1');
		}
		return $items;
	}

	static function listProductComingsoon($cache_name=null, $cache_time=610, $clear_cache=false) {
		if ($cache_name==null) $cache_name = 'comingsoon_product_'.CPortal::$estore_id;
		if (DEBUG || $clear_cache || !($items = CSystem::$cachedata->get($cache_name))) {
			$items = array_values(CTable('product')->fields('id,name,unsigned_name,category_id,thumbnail,warranty,cache_properties, price,special_image,product_vip'.CProduct::$conditionDefault)->select_all(
				EAnd(
					EOr(ELIKE('types',EString('.comingsoon.')), EAnd(EEqual('product_vip',1),ENE('special_image',EString('')),ELIKE('types',EString('.comingsoon.')))),
					EGT('price',EString(0)),EGT('min_price',EString(0)),
					EGT('market_price',EString(0)),EGT('status',EString(0)),
					EGT('quantity',EString(0))
				),
				array('order_by'=>'product_vip desc, created_time desc', 'items_per_page'=>5)
			));

			foreach ($items as &$item) {
				$item['name_short'] = CString(strip_tags($item['name']))->trim(20);
				$unsigned_name = isset($item['unsigned_name']) ? $item['unsigned_name'] : '';
				$param = array( 'id' => $item['id'], 'name' => $item['name'], 'category_id' => $item['category_id'], 'unsigned_name' => $unsigned_name);
				$item['onclick'] = url('product_detail', $param) . ' return false';
				$item['href'] = url('product_detail', $param, '', '1');
			}
			$items = CProductDetail::getProductDetailList($items);
			CSystem::$cachedata->set($cache_name, $items, $cache_time);
		}
		return $items;
	}

	static function get_hot_products($cache_name=null, $cache_time=605, $clear_cache=false) {
		if ($cache_name==null) $cache_name = 'hot_products_'.CPortal::$estore_id;
		if (DEBUG || $clear_cache || !($items = CSystem::$cachedata->get($cache_name))) {
			$items = array_values(CTable('product')->fields('id,name,unsigned_name,category_id,thumbnail,warranty,cache_properties, price'.CProduct::$conditionDefault)->select_all(
				EAnd(
					ELIKE('types',EString('.hot.')),
					ENE('category_id','phukien')
//					,
//					EGT('price',EString(0)),EGT('min_price',EString(0)),
//					EGT('market_price',EString(0)),EGT('status',EString(0)),
//					EGT('quantity',EString(0))
				),
				array('order_by'=>'created_time desc', 'items_per_page'=>8,'page_no'=>request('page_no',0)+1,)
			));
			foreach ($items as &$item) {
				$item['name_short'] = CString(strip_tags($item['name']))->trim(15);
				$unsigned_name = isset($item['unsigned_name']) ? $item['unsigned_name'] : '';
				$param = array( 'id' => $item['id'], 'name' => $item['name'], 'category_id' => $item['category_id'], 'unsigned_name' => $unsigned_name);
				$item['onclick'] = url('product_detail', $param) . ' return false';
				$item['href'] = url('product_detail', $param, '', '1');
			}
			if(count($items) > 0){
				$items = CProductDetail::getProductDetailList($items);
			}
			CSystem::$cachedata->set($cache_name, $items, $cache_time);
		}
		return $items;
	}
	
	static function get_not_hot_products($cache_name=null, $cache_time=605, $clear_cache=false) {
		if ($cache_name==null) $cache_name = 'not_hot_products_'.CPortal::$estore_id;
		if (DEBUG || $clear_cache || !($items = CSystem::$cachedata->get($cache_name))) {
			$items = array_values(CTable('product')->fields('id,name,unsigned_name,category_id,thumbnail,warranty,cache_properties, price'.CProduct::$conditionDefault)->select_all(
				EAnd(
					ENLIKE('types',EString('.hot.')),
					ENE('category_id','phukien')
//					,
//					EGT('price',EString(0)),EGT('min_price',EString(0)),
//					EGT('market_price',EString(0)),EGT('status',EString(0)),
//					EGT('quantity',EString(0))
				),
				array('order_by'=>'created_time desc', 'items_per_page'=>100)
			));
			foreach ($items as &$item) {
				$item['name_short'] = CString(strip_tags($item['name']))->trim(15);
				$unsigned_name = isset($item['unsigned_name']) ? $item['unsigned_name'] : '';
				$param = array( 'id' => $item['id'], 'name' => $item['name'], 'category_id' => $item['category_id'], 'unsigned_name' => $unsigned_name);
				$item['onclick'] = url('product_detail', $param) . ' return false';
				$item['href'] = url('product_detail', $param, '', '1');
			}
			if(count($items) > 0){
				$items = CProductDetail::getProductDetailList($items);
			}
			CSystem::$cachedata->set($cache_name, $items, $cache_time);
		}
		return $items;
	}
	
	static function get_top_hot_products($cache_name=null, $cache_time=605, $clear_cache=false) {
		if ($cache_name==null) $cache_name = 'hot_products_'.CPortal::$estore_id;
		if (DEBUG || $clear_cache || !($items = CSystem::$cachedata->get($cache_name))) {
			$items = array_values(CTable('product')->fields('id,name,unsigned_name,category_id,special_image,warranty,cache_properties, price'.CProduct::$conditionDefault)->select_all(
				EAnd(
					ELIKE('types',EString('.hot.'))
				),
				array('order_by'=>'created_time asc', 'items_per_page'=>30)
			));
			foreach ($items as &$item) {
				$item['name_short'] = CString(strip_tags($item['name']))->trim(15);
				$unsigned_name = isset($item['unsigned_name']) ? $item['unsigned_name'] : '';
				$param = array( 'id' => $item['id'], 'name' => $item['name'], 'category_id' => $item['category_id'], 'unsigned_name' => $unsigned_name);
				$item['onclick'] = url('product_detail', $param) . ' return false';
				$item['href'] = url('product_detail', $param, '', '1');
			}
			CSystem::$cachedata->set($cache_name, $items, $cache_time);
		}
		return $items;
	}

	static function getListProductSaleOff($cache_name=null, $cache_time=605, $clear_cache=false, $limit=3) {
		if ($cache_name==null) $cache_name = 'saleoff_products_'.$limit.CPortal::$estore_id;

		if (DEBUG || $clear_cache || !($items = CSystem::$cachedata->get($cache_name))) {
			$time = time();
			$endTime = $time-24*3600+1;
			$sql = "
select * from (
		select
			id,name,unsigned_name,reference_id,category_id,thumbnail,small,warranty,cache_properties, price,discount_percent,last_modify_time,
			(discount_maximum_items-discount_items) as b,
			if(reference_id='', code, reference_id) as fakeid, tax
		from product
		where (quantity>0)and(price>0)and(min_price>0)and(market_price>0)and
					(status>0)and(discount_percent>0)and(discount_start_date<=$time)and(discount_end_date>$endTime)and
					(discount_maximum_items-discount_items)>0 order by fakeid, b desc
) as SaleOff
group by fakeid order by last_modify_time desc limit $limit";

			$db = CStore::$default;
			$items = array();
			while ($item = $db->fetch($sql)) {
				$sql = false;
				$item['price_saleoff'] = ceil($item['price'] - (($item['price']*$item['discount_percent'])/100));
				$item['cache_properties'].='<strong>Thời gian bảo hành</strong>:&nbsp;'.$item['warranty'].'&nbsp;tháng';
				if ($item['thumbnail']=='') $item['thumbnail'] = $item['small'];
				$unsigned_name = isset($item['unsigned_name']) ? $item['unsigned_name'] : '';
				$param = array( 'id' => $item['id'], 'name' => $item['name'], 'category_id' => $item['category_id'], 'unsigned_name' => $unsigned_name);
				$item['onclick'] = url('product_detail', $param) . ' return false';
				$item['href'] = url('product_detail', $param, '', '1');
				$item['name_short'] = CString(strip_tags($item['name']))->trim(15);
				$items[] = $item;
			}
			$items = CProductDetail::getProductDetailList($items);
			CSystem::$cachedata->set($cache_name, $items, $cache_time);
		}
		return $items;
	}

	static function getFeatureProduct($type = 'new') {
		$condition = 'new';
		$sCondition = EAnd(EGT('price',EString(0)),EGT('min_price',EString(0)),
				EGT('market_price',EString(0)),EGT('status',EString(0)),
				EGT('quantity',EString(0)));
		switch($type){
			case 'saleoff':
				$sCondition = EAnd($sCondition,EEqual('reference_id',EString('')),ENE('discount_percent',EInt(0)), ELTE('discount_start_date',EInt(time())),EGT('discount_end_date',EInt(time()-24*3600+1)),
				 ELT('discount_items',E('discount_maximum_items')));
				break;
			case 'comingsoon':
				$condition = 'comingsoon';
				break;
			case 'special':
				$condition = 'special';
				break;
			case 'hot':
				$condition = 'hot';
				break;
			case 'new':
			default:
				break;
		}
		if($type != 'saleoff'){
			$sCondition = EAnd($sCondition,ELIKE('types',EString('.'.$condition.'.')) );
		}

		$items = CTable('product')->fields(
			'id,name,unsigned_name,category_id,thumbnail,warranty,cache_properties,
			price,special_image,product_vip,types'.CProduct::$conditionDefault)->select(
			$sCondition,
			array('order_by'=>'created_time desc')
		);
		if($type == 'saleoff' and !empty($items['discount_percent'])){
			$items['price_saleoff'] = ceil($items['price'] - (($items['price']*$items['discount_percent'])/100));
		}
		if($items){
			$unsigned_name = isset($item['unsigned_name']) ? $item['unsigned_name'] : '';
			$param = array( 'id' => $items['id'], 'name' => $items['name'], 'category_id' => $items['category_id'], 'unsigned_name' => $unsigned_name);
			$items['onclick'] = url('product_detail', $param) . ' return false';
			$items['href'] = url('product_detail', $param, '', '1');
			$items['name_short'] = CString(strip_tags($items['name']))->trim(15);
			$items = array($items);
			$items = CProductDetail::getProductDetailList($items);
		}
		return $items;
	}

	static function field_table($category_id, $table = 'groups/group')
	{
		if($category = CProduct::category($category_id))
		{
			$portal = portal()->id;
			if($portal == 'kultech'){
				$portal = 'default';
			}
			while($portal)
			{
				//if(CFile::exists($file_name = 'data/'.$portal.'/product_fields/'.$category['original_id'].'.xml'))
				if(CFile::exists($file_name = 'data/'.$portal.'/product_categories/'.$category['char_seo'].'.xml'))
				{
					return CTable($table)->change_store(new CDataXmlStore($file_name));
				}
				if($portal == 'default')
				{
					break;
				}
				if(isset(CPortal::$components['PORTAL.'.$portal]['parent']))
				{
					$portal = CPortal::$components['PORTAL.'.$portal]['parent'];
				}
				else
				{
					break;
				}
			}
		}
		return false;
	}

	static function synchronize_quantity(){
		$product_codes = CTable('product_store')->select_all(false, array('fields'=>'product_code','items_per_page'=>100000));
		foreach ($product_codes as $key=>$product_code){
			unset($product_codes[$key]);
			if(!in_array($product_code, $product_codes)){
				$sum = CTable('product_store')
					->fields('sum(quantity) as total')
					->condition(EEqual('product_code',$product_code['product_code']))
					->select_value();
				CTable('product')->update(array('quantity'=>$sum),EEqual('code',EString($product_code['product_code'])));
			}
		}
	}
}
?>
